/*
 * =====================================================================================
 *
 *       Filename:  regular.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  03/06/2018 05:36:11 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "regular.h"
#include <string.h>

CReg::CReg():
    m_compiled(false)
{}

CReg::~CReg()
{
    if (m_compiled)
        regfree(&m_reg);
}

bool CReg::isMatch(const string& pattern,const string& str)
{
    if (m_compiled)
    {
        regfree(&m_reg);
        m_compiled = false;
    }
    
    if (regcomp(&m_reg, pattern.c_str(), REG_EXTENDED | REG_NEWLINE | REG_NOSUB)!=0 )
    {
        regfree(&m_reg);
        return false;
    }

    m_compiled = true;

    return (regexec(&m_reg,str.c_str(),0,NULL,0) == 0);
}

/*
bool CReg::isMatch(const string& pattern,const string& str,
        vector<string>& matchs,unsigned int nums)
{
    if (m_compiled)
    {
        regfree(&m_reg);
        m_compiled = false;
    }
    
    if (regcomp(&m_reg, str.c_str(),REG_EXTENDED )!=0 )
    {
        regfree(&m_reg);
        return false;
    }

    m_compiled = true;

    if (nums < 0)
        return false;
   
    regmatch_t* pregmatchs = new regmatch_t[nums+1];
    memset(pregmatchs,0,sizeof(regmatch_t)*(nums+1));
    int ret = regexec(&m_reg,str.c_str(),nums,pregmatchs,0);
    if (ret != 0)
    {
        delete [] pregmatchs;
        return false;
    }

    for(int i = 0; i < nums + 1; ++i)
    {
        cout<<"i:"<<i<<endl; 
        cout<<"so:"<<pregmatchs[i].rm_so<<endl; 
        cout<<"eo:"<<pregmatchs[i].rm_eo<<endl; 
        if (pregmatchs[i].rm_so != -1)
        {
            char buf[64] = {0};
            strncpy(buf,(str.c_str() + pregmatchs[i].rm_so),pregmatchs[i].rm_eo);
            cout<<buf<<endl;
        }
    }
    delete [] pregmatchs;

    return ret == 0;
}
*/














